package com.star.redis;

import redis.clients.jedis.Jedis;

import java.util.Collections;

public class RedisPoolUtil {

    private static final String LOCK_SUCCESS = "OK";
    private static final String SET_IF_NOT_EXIST = "NX";
    private static final String SET_WITH_EXPIRE_TIME = "PX";

    private RedisPoolUtil(){}
    /**
     * 
     * @param jedis 
     * @param lockKey 加锁
     * @param requestId 请求的标志位
     * @param expireTime 超时时间
     * @return
     */
    public static boolean tryGetDistributedLock(Jedis jedis, String lockKey, String requestId, int expireTime) {

        String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);

        if (LOCK_SUCCESS.equals(result)) {
            return true;
        }else{
            try{
                Thread.sleep(10);//休眠100毫秒
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        return false;
    }


    public static boolean releaseDistributedLock(Jedis jedis, String lockKey, String requestId) {

        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));

        if ("OK".equals(result)) {
            return true;
        }
        return false;

    }


    /*


jedis示例代码

    try{
        Boolean result = RedisPoolUtil.tryGetDistributedLock(jedis, "xxxxx", uuid, 5000);

        if(result) {
            xxxx代码片段
        }else{

        }

    }catch(){

    }finally{
        RedisPoolUtil.releaseDistributedLock(jedis,"xxxxx", uuid);
    }*/

}